package http

import (
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"net/http"
	"net/http/httputil"
	"runtime"
	"time"

	"github.com/gin-gonic/gin"
)

type Middleware struct {
	log *log.Helper
}

func NewMiddleware(logger log.Logger) *Middleware  {
	return &Middleware{log: log.NewHelper(logger)}
}

func (m *Middleware) LoggerHandler(c *gin.Context) {
	// Start timer
	start := time.Now()
	path := c.Request.URL.Path
	raw := c.Request.URL.RawQuery
	method := c.Request.Method

	// Process request
	c.Next()

	// Stop timer
	end := time.Now()
	latency := end.Sub(start)
	statusCode := c.Writer.Status()
	ecode := c.GetInt(contextErrCode)
	clientIP := c.ClientIP()
	if raw != "" {
		path = path + "?" + raw
	}
	m.log.Infof("METHOD:%s | PATH:%s | CODE:%d | IP:%s | TIME:%d | ECODE:%d", method, path, statusCode, clientIP, latency/time.Millisecond, ecode)
}

func (m *Middleware) RecoverHandler(c *gin.Context) {
	defer func() {
		fmt.Println("244422222444")
		if err := recover(); err != nil {
			const size = 64 << 10
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			httprequest, _ := httputil.DumpRequest(c.Request, false)
			pnc := fmt.Sprintf("[Recovery] %s panic recovered:\n%s\n%s\n%s", time.Now().Format("2006-01-02 15:04:05"), string(httprequest), err, buf)
			fmt.Print(pnc)
			m.log.Error(pnc)
			c.AbortWithStatus(500)
		}
	}()
	c.Next()
}

func AuthMiddleware() gin.HandlerFunc  {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			c.Abort()
			c.JSON(http.StatusUnauthorized, map[string]string{
				"msg":"非法请求",
			})
			return
		}
	}
}